//index.js
var common = require('../../lib/common.js')
const app = getApp()
const game_code = 'ldtj' // 游戏编码

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    loadConfig: false,
    logged: false,
    takeSession: false,
    requestResult: '',
    gps: '',
    lat: '',
    lng: '',
    acc: '',
  },

  onLoad: function() {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    console.log('get user info')
    wx.getSetting({
      success: res => {
        console.log(res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // console.log('userinfo', res.userInfo)
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        } else {
          wx.showModal({
            title: '信息',
            content: '请点击登录',
          })
        }

        let self = this

        if (res.authSetting['scope.userLocation']) {
          this.setData({
            gps: 'ok'
          })
          self.onGetPosition()
          // setInterval(function () {
          //   }, 1000)
        } else {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              console.log('auth gps', self)
            }
          })
          this.setData({
            gps: 'error'
          })
        }
      }
    })
  },

  onGetPosition: function(e) {
    // console.log('onGetPosition', this)
    let self = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        // console.log('wx.getLocation', self)
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        self.setData({
          lat: res.latitude,
          lng: res.longitude,
          acc: res.accuracy
        })
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onInitGame: function() {
    // 1、调用云函数获取openid，通过openid获取用户记录
    wx.cloud.callFunction({
      name: 'login',
      data: {},
    }).then(res => {
      // 成功获取openid
      app.globalData.openid = res.result.openid

      // 2、获取游戏基础数据
      common.get_record_list(game_code, app.globalData.openid)
    }).catch(err => {
      console.error('login调用失败', err)
      wx.showModal({
        title: 'login失败',
        content: err,
      })
    })

    // 3、启动定时器，检查游戏信息载入状态
    setTimeout(() => {
      this.checkLoadStatus()
    }, 1000)
  },

  checkLoadStatus: function(config_data) {
    if ('config' in app.globalData) {
      // console.log('checkLoadStatus OK', app.globalData)
      this.setData({
        loadConfig: true,
      })
    } else {
      // 启动定时器，检查游戏信息载入状态
      setTimeout(() => {
        this.checkLoadStatus()
      }, 1000)
    }
  },

  // 上传图片
  doUpload: function() {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]

        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

  getConfig: function() {
    // common.getGameConfig('ldtj', this)
    // common.getRecordList('ldtj', 'oe3wB5SAUc6g6TRW6bp99kc37Q3s')

    let foo = this.initData()
    foo.then(res => {
      console.log('end1')
    })

    console.log('end')
  },

  initData: function() {
    return new Promise((resolve, reject) => {
      // 在 3 秒后返回结果给调用方（小程序 / 其他云函数）
      setTimeout(() => {
        console.log('time out')
        resolve('event.userInfo.openId')
      }, 3000)
    })

  },

  doResetRecord: function() {
    common.reset_record_list()
    // if ('config' in app.globalData) {
    //   wx.setStorageSync('key', '我是同步存储的数据')
    //   wx.navigateTo({
    //     url: '../checkpoint/checkpoint'
    //   })
    // } else {
    //   wx.showToast({
    //     title: '请等待...',
    //     icon: 'loading',
    //   })
    // }
  },

})